﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MetroCashLib;
using MetroCashLib.DataInfo;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MetroCash
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class PCreateProfile : MetroCash.Common.LayoutAwarePage
    {
        private string installedDBFilePath = String.Empty;
        private ResourceLoader resLoader;
        public PCreateProfile()
        {

            this.InitializeComponent();

            Loaded += PCreateProfile_Loaded;
        }


        async void PCreateProfile_Loaded(object sender, RoutedEventArgs e)
        {
            this.resLoader = new ResourceLoader();
            //this.pageTitle.Text = this.resLoader.GetString("Profile-New-Create");
            //this.lblNewProfileName.Text = this.resLoader.GetString("Profile-New-Name");
            //this.lblNewProfileCurrency.Text = this.resLoader.GetString("Profile-New-Currency");
            //(this.btnCreateProfile.Content as TextBlock).Text = this.resLoader.GetString("Common-Create");
            //this.txtProfileName.Text = this.resLoader.GetString("Profile-New-Name-Placeholder");
            this.installedDBFilePath = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "MetroCashLib\\StartUpDB\\StartUp.metrocash");
            try
            {
                StorageFile seedFile = await StorageFile.GetFileFromPathAsync(this.installedDBFilePath);
                if (seedFile == null)
                {
                    // for further uses
                }
            }
            catch (Exception)
            {
                this.installedDBFilePath = String.Empty;
            }

            // Check for the existence of the installedDBFile
            if (String.IsNullOrEmpty(this.installedDBFilePath))
            {
                var quitMsg = new MessageDialog("There is a problem with your installation. We cannot find the required data file. Reinstall this application may be fix this problem.", "Application Error");
                quitMsg.Commands.Add(new UICommand("Quit", (UICommandInvokedHandler) =>
                {
                    Application.Current.Exit();
                }));
                await quitMsg.ShowAsync();
            }

            using (var db = new SQLite.SQLiteConnection(this.installedDBFilePath))
            {
                try
                {
                    List<Currency> avaiCurrencies = new List<Currency>();
                    avaiCurrencies = db.Query<Currency>("select * from Currency").ToList<Currency>();
                    this.cbbProfileCurrency.DataContext = avaiCurrencies;
                    this.cbbProfileCurrency.SelectedIndex = 0;
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void btnCreateProfile_Click_1(object sender, RoutedEventArgs e)
        {
            this.createProfile(this.txtProfileName.Text, this.cbbProfileCurrency.SelectedItem as Currency);
        }

        async private void createProfile(string profileName, Currency currency)
        {
            var seedFile = await StorageFile.GetFileFromPathAsync(this.installedDBFilePath);

            var profileFolder = await Windows.Storage.ApplicationData.Current.RoamingFolder.CreateFolderAsync(SettingStrings.PROFILE_FOLDER_NAME, CreationCollisionOption.OpenIfExists);


            bool copyOK = true;
            try
            {
                var result = await seedFile.CopyAsync(profileFolder, profileName, NameCollisionOption.FailIfExists);
            }
            catch (Exception ex)
            {
                copyOK = false;
                var quitMsg = new MessageDialog(String.Format(this.resLoader.GetString("Error-Body-NewProfile-Duplicate"), this.txtProfileName.Text), this.resLoader.GetString("Error-Header-Input"));
                quitMsg.Commands.Add(new UICommand(this.resLoader.GetString("Error-Button-NewProfile-Duplicate-OK")));
                quitMsg.ShowAsync();
            }

            if (copyOK)
            {
                using (var db = new SQLite.SQLiteConnection(Path.Combine(profileFolder.Path,profileName)))
                {
                    // create tables
                    List<AccountType> accountTypes = db.Query<AccountType>("select * from AccountType").ToList<AccountType>();
                    db.RunInTransaction(() =>
                    {
                        foreach (AccountType type in accountTypes)
                        {
                            db.Insert(new Account() { Id = type.Id, AccountTypeId = type.Id, AccountParentId = type.ParentId, isPlaceHolder = true, CurrencyId = currency.Id, Name = type.Name, Description = type.Description });
                        }
                    });
                    db.Close();
                }
                Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
                roamingSettings.Values[SettingStrings.ROAMING_CURRENT_PROFILE] = profileName;
                this.Frame.GoBack();
            }
        }
    }
}
